package com.clusterswisdom.horn.api.tmall.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.internal.util.WebUtils;

public class AccessToken {
	
	/**
	 * @doc http://www.qq7u.com/develop/2012-07-10/876.html
	 * @doc http://open.taobao.com/doc/detail.htm?spm=a219a.7386781.0.0.oZWsIV&id=118
	 * @doc https://oauth.taobao.com/oauth2?view=authCode#authCode=TOP-10bfe0b1586a7c1fb9760364b302c19071vMF7mYwhtDINZk57cMla32NuduXkbK-END
	 * @doc http://www.cnblogs.com/jerrmy/archive/2013/08/20/3268856.html
	 * @param args
	 */
	public static void main(String[] args) {
		
			String authcode = authcode();
			
			//String token = accessToken(authcode);
			
			/**
			 * 最终的accessToken
			 */
			System.out.println(authcode);
	}
	
	/**
	 * 第一步 ： 拿到授权码
	 * @doc http://open.taobao.com/doc/detail.htm?spm=a219a.7386781.0.0.oZWsIV&id=118
	 * @return
	 */
	public static String authcode(){
		String url="https://oauth.taobao.com/authorize";
		 
	      Map<String,String> props=new HashMap<String,String>();
	      
	      props.put("client_id","23067114");
	      props.put("response_type","code");
	      props.put("redirect_uri","http://www.miqiling.com");
	      //props.put("view","web");
	      String s = "";
	      
	      /**
	       * {code: '授权码', error: '', error_description: ''}
	       */
	      try{
	    	  
	    	  	s = WebUtils.doPost(url, props, 30000, 30000);
	      		System.out.println(s);
	      }catch(IOException e){
	          e.printStackTrace();
	      }
	      
	      System.out.println(s);;
	      
	      //JSONObject jo = JSONObject.parseObject(s);
	      return "";
	      /**
	       * 授权码
	       */
	     // return jo.getString("code");
	}
	
	/**
	 * 第二步 ： 通过令牌获得会话ID( accessToken 或者叫 SessionKey)
	 * @param authcode
	 * @doc http://open.taobao.com/doc/detail.htm?spm=a219a.7386781.0.0.oZWsIV&id=118
	 * @return
	 */
	public static String accessToken(String authcode){
		String url="https://oauth.taobao.com/token";
		 
	      Map<String,String> props=new HashMap<String,String>();
	      
	      props.put("client_id","23063996");
	      props.put("client_secret","3w5232342532");
	      props.put("grant_type", "authorization_code");
	      props.put("code", authcode); // 填入授权码	
	      props.put("redirect_uri","http://www.test.com");
	      props.put("view","web");
	      
	      String s = "";
	      
	      /**
	       * {code: '授权码', error: '', error_description: ''}
	       */
	      try{
    	  		s = WebUtils.doPost(url, props, 30000, 30000);
      			System.out.println(s);
	      }catch(IOException e){
	    	  e.printStackTrace();
	      }
	      
	      JSONObject jo = JSONObject.parseObject(s);
	      
	      return jo.getString("access_token");
	}
}
